var express = require('express')
var router = express.Router()
const alipaySdk = require('../db/alipayUtil')
const AlipayFormData = require('alipay-sdk/lib/form').default
const cors = require('cors')
router.use(cors())
router.use(express.urlencoded({ extended: true }))
/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' })
})

router.post('/api/payment', async function (req, res, next) {
  console.log(222)
  const orderId = req.body.orderId
  console.log(orderId)
  const formData = new AlipayFormData()
  formData.setMethod('get')

  formData.addField('returnUrl', 'http://localhost:8081/pay-success')
  formData.addField('bizContent', {
    outTradeNo: orderId,
    productCode: 'FAST_INSTANT_TRADE_PAY',
    totalAmount: '0.01',
    subject: '商品',
    body: '商品详情'
  })
  const result = await alipaySdk.exec(
    'alipay.trade.page.pay',
    {},
    { formData: formData }
  )
  console.dir(result)
  res.send({
    success: 'true',
    code: 200,
    result: result
  })
  // result.then(resp => {
  //   res.send({
  //     success: 'true',
  //     code: 200,
  //     result: resp
  //   })
  // })
})

module.exports = router
